package com.jijs.framework.core.taglib;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.jijs.framework.model.pmodel.AdeDictionary;
import com.jijs.framework.service.DictionaryManagerService;
import com.jijs.framework.util.SpringBeanUtil;

/**
 * 字典打印标签
 * 
 * @author jijs
 * 
 */
public class DictionaryPrintTag extends TagSupport {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 4989829376376068900L;

	private static final String FIELD_VALUE = "value";
	private static final String FIELD_NAME = "name";

	/**
	 * 编码
	 */
	private String code = null;

	/**
	 * 选择打印value或者name
	 */
	private String field = FIELD_VALUE;

	public void setField(String field) {
		this.field = field;
	}

	public void setCode(String code) {
		this.code = code;
	}

	@Override
	public int doEndTag() throws JspException {

		DictionaryManagerService service = (DictionaryManagerService) SpringBeanUtil
				.getBean("dictionaryManagerService");

		if (service == null) {
			throw new JspException("找不到数据字典对应的服务类");
		}

		AdeDictionary dict = service.getDictionaryByDictCode(code);

		if (dict == null) {
			throw new JspException("找不到[" + code + "]对应的数据字典！");
		}

		String print = null;

		if (FIELD_VALUE.equals(field)) {
			print = dict.getDictValue();
		} else if (FIELD_NAME.equals(field)) {
			print = dict.getDictName();
		} else {
			throw new JspException("field对应设置的属性找不到，请设置为value或者name");
		}

		JspWriter writer = null;

		try {
			writer = pageContext.getOut();
			writer.write(print);
			writer.flush();
		} catch (IOException e) {
			throw new JspException(e);
		}

		return TagSupport.EVAL_PAGE;
	}
}
